package com.chii.order.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.chii.order.client.UserClient;
import com.chii.order.po.Order;
import com.chii.order.po.ResponeInfo;
import com.chii.order.service.OrderService;
import com.chii.order.service.PtcAlipayService;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Api(value = "PayController", tags = {"支付操作"})
@RestController
public class PayController {
    private Logger logger = LogManager.getLogger(PayController.class);
    @Value("${alipay.alipay_public_key}")
    private String alipay_public_key;
    @Autowired
    private PtcAlipayService ptcAlipayService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserClient userClient;
    /**
     * 支付宝回调信息.
     *
     * @param request the request
     * @return the object
     */
    @RequestMapping(value = "/alipayCallback", method = RequestMethod.POST)
    public String alipayCallback(HttpServletRequest request) throws AlipayApiException {
        ResponeInfo responeInfo = new ResponeInfo();
        logger.info("收到支付宝回调信息");
        Map<String, String> params = Maps.newHashMap();

        Map requestParams = request.getParameterMap();
        for (Object o : requestParams.keySet()) {
            String name = (String) o;
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        logger.info("支付宝回调,sign:{},trade_status:{},参数:{}", params.get("sign"), params.get("trade_status"), params.toString());

        //非常重要,验证回调的正确性,是不是支付宝发的.并且呢还要避免重复通知.
        params.remove("sign_type");

        boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, alipay_public_key, "utf-8", "RSA2");

        if (!alipayRSACheckedV2) {
            responeInfo.failure("非法请求,验证不通过,再恶意请求我就报警找网警了");
            return "failure";
        }
        Order order  = orderService.getOrder(params.get("out_trade_no"));
        ptcAlipayService.aliPayCallback(params.get("out_trade_no"));
        userClient.insertRole(order.getUid(), "vip");

        return "success";
    }

    /**
     * todo 开发用
     * @param orderNo
     * @return
     * @throws AlipayApiException
     */
    @RequestMapping(value = "/alipayReturn", method = RequestMethod.POST)
    public ResponeInfo alipayReturn(@ApiParam(name = "orderNo", value = "订单号") @RequestParam("orderNo") String orderNo) throws AlipayApiException {
        ResponeInfo responeInfo = new ResponeInfo();
        Order order  = orderService.getOrder(orderNo);
        ptcAlipayService.aliPayCallback(orderNo);
        userClient.insertRole(order.getUid(), "vip");
        return responeInfo;
    }


    @RequestMapping(value = "/ali_pay", method = RequestMethod.POST)
    public ResponeInfo pay(@ApiParam(name = "orderNo", value = "订单号") @RequestParam("orderNo") String orderNo,
                           @ApiParam(name = "orderDescription", value = "订单描述") @RequestParam("orderDescription") String orderDescription) throws AlipayApiException {
        ResponeInfo responeInfo = new ResponeInfo();
        String s = ptcAlipayService.pay(orderNo, orderDescription);
        responeInfo.setData(s);
        return responeInfo;
    }


}
